import type { IResizeOptions } from "@/types/useResize";
import { useDebounceFn } from "@vueuse/core";

// - 默认适配宽高
export const width = 1920;
export const height = 1080;

// - 适配屏幕
export const useResize = (options: IResizeOptions = {}) => {
  const { w = width, h = height, fullscreen = false, delay = 0 } = options;

  // - 获取屏幕元素
  const screenRef = useTemplateRef<HTMLElement>("screenRef");
  // - 获取缩放比例
  const scale = ref(1);

  // * 尺寸变化
  const resize = () => {
    // - 获取浏览器宽沟
    const clientWidth = document.body.clientWidth;
    const clientHeight = document.body.clientHeight;

    // - 计算缩放比例
    const scaleW = clientWidth / w;
    const scaleH = clientHeight / h;
    scale.value = Math.min(scaleW, scaleH);

    if (fullscreen) {
      // - 如果全屏，则直接把宽高按比例缩放，确保无黑边，但是会失帧
      screenRef.value!.style.transform = `scale(${scaleW}, ${scaleH})`;
    } else {
      screenRef.value!.style.transform = `scale(${scale.value})`;

      // - 设置居中
      screenRef.value!.style.left = `${(clientWidth - w * scale.value) / 2}px`;
      screenRef.value!.style.top = `${(clientHeight - h * scale.value) / 2}px`;
    }
  };

  // - 防抖处理
  const delayResize = useDebounceFn(resize, delay);

  // - 监听窗口变化
  onMounted(() => {
    if (screenRef.value) {
      resize();
      window.addEventListener("resize", delayResize);
    }
  });

  onBeforeUnmount(() => {
    window.removeEventListener("resize", delayResize);
  });

  return {
    screenRef,
    scale,
  };
};
